﻿using Newtonsoft.Json;
using NPOI.OpenXmlFormats.Dml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MDT.LifeSewagePlatform.Conmmon
{
    public class FileHelper:IFileHelper
    {
        private FileStream fs { get; set; }
        private readonly static  object _lock=new object();

        public FileHelper()
        {

        }
        public void SetFileStream(string filePath)
        {
            if (fs != null)
            {
                fs.Close();
                fs.Dispose();
            }

            fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        }

        public async Task<T> GetEntity<T>()
        {

            if (fs == null)
                return default(T);

            using (StreamReader sr = new StreamReader(fs))
            {
                string strContent = await sr.ReadToEndAsync();
                T t = JsonConvert.DeserializeObject<T>(strContent);
                return t;

            }
        }

        public  bool UpdateFileContent<T>(T t)
        {
            bool IsOk = true;
            if (fs == null)
                IsOk = false;
            using (StreamWriter sw = new StreamWriter(fs))
            {
                try
                {
                    lock (_lock)
                    {
                    string strJson = JsonConvert.SerializeObject(t);
                    sw.Write(strJson);
                    sw.Flush();
                    fs.Flush();
                    sw.Close();
                    fs.Close();
                    }
                }
                catch (Exception)
                {
                   IsOk = false;
                }
                finally { }
            }
            return IsOk;
        }
    }
}
